package com.blue.wechat.invoke.spi.oauth;

import java.text.MessageFormat;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;

import com.blue.http.client.HttpInvoker;
import com.blue.wechat.cache.Wechat;
import com.blue.wechat.cache.WechatCache;
import com.blue.wechat.invoke.InvokeException;
import com.blue.wechat.invoke.Invoker;
import com.blue.wechat.invoke.WechatInvokeUtil;
import com.blue.wechat.invoke.WechatInvoker;
import com.blue.wechat.invoke.annotation.WechatUrl;
import com.blue.wechat.invoke.model.user.UserInfo;

/**
 * 网页授权获取用户信息
 * 
 * @author zhengj
 * @since 1.0 2017年1月30日
 */
@WechatUrl(WechatInvoker.OAUTH_USER_INFO)
public class OAuthUserInfoInvoker implements Invoker<UserInfo>
{
	private static final WechatInvoker INVOKER = WechatInvoker.OAUTH_USER_INFO;

	@Resource
	private HttpInvoker httpInvoker;
	@Resource
	private WechatCache wechatCache;
	
	public OAuthUserInfoInvoker()
	{
	}

	@Override
	public UserInfo invoke(String code, Object post, String... get) throws InvokeException
	{
		Wechat wechat = wechatCache.getByCode(code);
		if (wechat == null)
			throw InvokeException.getException(InvokeException.WECHAT_NOT_FOUND + code);
		
		Object[] params = new Object[get.length];
		for (int i = 0; i < get.length; i++)
		{
			params[i] = get[i];
		}
		String url = MessageFormat.format(INVOKER.getUrl(), params);
		String resp = null;
		long start = System.currentTimeMillis();
		try
		{
			resp = httpInvoker.get(url);
			UserInfo user = WechatInvokeUtil.toResponse(resp, UserInfo.class);
			WechatInvokeUtil.log(wechat.getName(), INVOKER.getName(), url, StringUtils.join(get, ","), null, (int)(System.currentTimeMillis() - start), resp, null);
			return user;
		}
		catch (Exception e)
		{
			WechatInvokeUtil.log(wechat.getName(), INVOKER.getName(), url, StringUtils.join(get, ","), null, (int)(System.currentTimeMillis() - start), e.getMessage(), e);
			throw InvokeException.getException(InvokeException.WECHAT_ACCESS_TOKEN_ERROR);
		}
	}
}
